import NewSelect from '@/components/NewSelect';
import { handleApplyOrder, handleCalculate, handleEvent, handleGetToken } from '@/services/center';
import { formatNumber } from '@/utils';
import { Button, Col, Flex, Form, InputNumber, Modal, Row, Space } from 'antd';
import { useEffect, useState } from 'react';
import { useIntl, useModel } from 'umi';
import ApplySucModal from './ApplySucModal';
type Props = {
  visible: boolean;
  handleCancel: () => void;
  data: Partial<Center.ProductList>;
  onOk?: (id: any) => void;
};
const ApplyNowModal: React.FC<Props> = ({ visible, handleCancel, data, onOk }) => {
  const intl = useIntl();
  const [form] = Form.useForm();
  const { user } = useModel('userModel');

  const { applyAmount } = user || {};
  const values = Form.useWatch([], form);
  const [num, setNumber] = useState(0);
  const [submittable, setSubmittable] = useState<boolean>(false);
  const {
    id,
    yearInterestMin,
    merchantLogo,
    merchantName,
    productName,
    applyNum,
    passRate,
    loanAmountMax,
    loanTermMax,
  } = data;
  const getMoney = async (cLoanTerm?: any) => {
    const { loanTerm, loanAmount } = values;
    const term = cLoanTerm || loanTerm;
    if (!(term && loanAmount)) {
      return;
    }
    const { data } = await handleCalculate({
      loanTerm: term,
      loanAmount,
      rate: yearInterestMin || 0,
    });
    setNumber(data);
  };
  useEffect(() => {
    if (visible && Object.keys(values || {}).length > 0) {
      form
        .validateFields({ validateOnly: true })
        .then(async () => {
          setSubmittable(true);
        })
        .catch(() => {
          setSubmittable(false);
        });
    } else {
      setSubmittable(false);
    }
  }, [form, values, visible]);

  const [modalVisible, setModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const descripList = [
    {
      key: 'loanAmountMax',
      title: 'home.max_loan_amount',
      formatFn: (value: number) => (
        <Space style={{ fontSize: 20, fontWeight: 700 }}>
          <div>$</div>
          <div>{formatNumber(value, false)}</div>
        </Space>
      ),
    },
    {
      key: 'loanTermMax',
      title: 'home.long_pay',
      formatFn: (value: number) => (
        <div style={{ fontSize: 14, fontWeight: 400 }}>
          {intl.formatMessage(
            { id: 'home.month' },
            { num: <span style={{ fontWeight: 700, fontSize: 20, marginRight: 5 }}>{value}</span> },
          )}
        </div>
      ),
    },
    {
      key: 'yearInterestMin',
      title: 'home.low_year_rate',
      formatFn: (value: number) => `${value}%`,
    },
  ];

  const options = new Array(loanTermMax).fill(0).map((_, index) => {
    const val = index + 1;
    return {
      value: val,
      label: (
        <div style={{ fontSize: 16, paddingLeft: 13, color: '#333' }}>
          {intl.formatMessage({ id: 'center.how_month' }, { num: val })}
        </div>
      ),
    };
  });

  return (
    <>
      <Modal
        className="apply_now_modal"
        onCancel={() => {
          handleCancel();
        }}
        footer={false}
        width={917}
        open={visible}
        centered
        destroyOnClose={true}
      >
        <Flex justify="space-between">
          <Space size={9}>
            <img src={merchantLogo} height={30} />
            <div style={{ fontSize: 20, color: '#0F294D', fontWeight: 400 }}>{merchantName}</div>

            <div style={{ fontSize: 20, color: '#0F294D', fontWeight: 700 }}>{productName}</div>
          </Space>
          <Space size={9}>
            <div
              style={{ background: '#FFEFE8', color: '#FF8F00', padding: '6.5px 10px' }}
              className="product_content_right_card_tag"
            >
              {intl.formatMessage({ id: 'home.send' }, { num: applyNum })}
            </div>
            <div
              style={{ background: '#E8F7FF', color: '#0065FD', padding: '6.5px 10px' }}
              className="product_content_right_card_tag"
            >
              <span style={{ fontWeight: 700 }}>
                {intl.formatMessage({ id: 'home.success_rate' })}
              </span>
              <span style={{ marginLeft: 5 }}>{passRate}%</span>
            </div>
          </Space>
        </Flex>
        <div
          style={{
            margin: '22px 0 14px',
            fontWeight: 700,
            fontSize: 17,
            lineHeight: '32px',
            color: '#333',
          }}
        >
          {intl.formatMessage({ id: 'home.operate_price' })}
        </div>
        <Flex gap={60} justify="space-between" align="center" style={{ margin: '15px 0 20px 0' }}>
          {descripList.map((v) => {
            const { key, title, formatFn } = v;
            return (
              <div
                style={{ background: '#FFF2EA', padding: '16px 40px', flex: 1, borderRadius: 6 }}
                key={key}
              >
                <div style={{ fontSize: 20, fontWeight: 700 }}>{formatFn(data[key])}</div>
                <div style={{ fontSize: 16, color: '#999', fontWeight: 700 }}>
                  {intl.formatMessage({ id: title })}
                </div>
              </div>
            );
          })}
        </Flex>

        <div style={{ fontSize: 16, color: '#000', margin: '30px 0 13px 0' }}>
          {intl.formatMessage({ id: 'center.loan' })}
        </div>

        <Form
          labelCol={{ span: 0 }}
          initialValues={{ loanAmount: applyAmount }}
          onFinish={async (values) => {
            setLoading(true);
            try {
              // const { data: val } = await getProductConfig({ pid: id?.toString() || '0' });
              // const { emptyField } = val;

              // if (emptyField.length !== 0) {
              //   jumpUrl(
              //     `/supplement?id=${id}&loanAmount=${values.loanAmount}&loanTerm=${values.loanTerm}`,
              //   );
              // } else {
              const { data } = await handleGetToken();

              await handleApplyOrder({
                apiToken: data,
                pid: id?.toString() || '',
                ...values,
              });
              if (onOk) {
                onOk(id);
              }
              handleCancel();

              setModalVisible(true);
              handleEvent('Plan_Application_Details_Submit');

              setLoading(false);
            } catch {
              setLoading(false);
            }
          }}
          preserve={false}
          form={form}
        >
          <Row gutter={[43, 0]}>
            <Col span={12}>
              <Form.Item
                name="loanAmount"
                label={intl.formatMessage({ id: 'center.get_money' })}
                rules={[{ required: true }]}
                className="apply_loanAmout"
              >
                <InputNumber
                  max={loanAmountMax}
                  controls={false}
                  style={{
                    borderRadius: 8,
                    background: '#F5F6F8',
                    width: '100%',
                    padding: '15px 24px',
                    fontSize: 16,
                  }}
                  onBlur={() => {
                    getMoney();
                  }}
                  variant="borderless"
                  prefix="$"
                  placeholder={intl.formatMessage({ id: 'center.get_money' })}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="loanTerm"
                label={intl.formatMessage({ id: 'center.time' })}
                rules={[{ required: true }]}
              >
                <NewSelect
                  onChange={(value) => {
                    getMoney(value);
                  }}
                  style={{
                    borderRadius: 8,
                    height: 60,
                    border: 'none',

                    background: '#F5F6F8',

                    width: '100%',
                  }}
                  placement="bottomLeft"
                  options={options}
                  variant="borderless"
                  placeholder={
                    <div style={{ fontSize: 16, paddingLeft: 13 }}>
                      {intl.formatMessage({ id: 'center.time' })}
                    </div>
                  }
                />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item noStyle>
            <Flex gap={16} align="center" style={{ marginTop: 10 }}>
              <div style={{ color: '#999', fontSize: 16 }}>
                {intl.formatMessage({ id: 'home.month_pay' })}
              </div>
              <div style={{ color: '#FF8F00', fontSize: 16 }}>$ {num}</div>
            </Flex>
          </Form.Item>

          <div style={{ color: '#999', margin: '16px 0 49px 0' }}>
            {intl.formatMessage({ id: 'home.apply_tips' })}
          </div>

          <Form.Item style={{ margin: '30px 0  0' }}>
            <Flex justify="center">
              <Button
                htmlType="submit"
                loading={loading}
                disabled={!submittable}
                type="primary"
                style={{
                  height: '60px',
                  minWidth: 200,
                  display: 'flex',
                  border: 'none',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <Space style={{ fontSize: 16 }}>
                  <div>{intl.formatMessage({ id: 'center.apply_now' })}</div>
                </Space>
              </Button>
            </Flex>
          </Form.Item>
        </Form>
      </Modal>
      <ApplySucModal
        handleCancel={() => {
          setModalVisible(false);
        }}
        data={data}
        visible={modalVisible}
      />
    </>
  );
};

export default ApplyNowModal;
